package que

import "errors"

type CircularQueueChannel struct {
	ch       chan interface{}
	capacity int
	head     int
	tail     int
	size     int
}

func NewCircularQueueChannel(capacity int) *CircularQueueChannel {

	return &CircularQueueChannel{
		ch:       make(chan interface{}, capacity),
		capacity: capacity,
		head:     0,
		tail:     0,
		size:     0,
	}
}

func (cq *CircularQueueChannel) Enqueue(value interface{}) error {
	select {
	case cq.ch <- value:
		cq.tail = (cq.tail + 1) % cq.capacity
		cq.size++
	default:
		return errors.New("channel 已满，丢弃数据")
	}

	return nil
}

func (cq *CircularQueueChannel) DeQueue() (interface{}, error) {
	if cq.size <= 0 {
		return nil, errors.New("队列没有数据")
	}
	value := <-cq.ch

	cq.head = (cq.head + 1) % cq.capacity
	cq.size--
	return value, nil
}

func (cq *CircularQueueChannel) Size() int {
	return cq.size
}

func (cq *CircularQueueChannel) Capacity() int {
	return cq.capacity
}
